package editor;

import java.awt.Container;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedList;

import javax.swing.JFileChooser;

public class Tileset 
{
	private String name;
	private LinkedList<String> tilesLocations;
	private LinkedList<Tile> tiles;
	
	public Tileset( String name, LinkedList<String> s )
	{
		this.name = name;
		tilesLocations = s;
		loadTiles();
	}
	
	public void loadTiles()
	{
		tiles = new LinkedList<Tile>();
		
		for( String s : tilesLocations )
		{
			tiles.add( Tile.load( s ) );
		}
	}
	
	public LinkedList<Tile> getTiles()
	{
		return tiles;
	}
	
	public Tile getTileWithKey( int key )
	{
		for( Tile t : tiles )
		{
			if( t.getKey() == key )
				return t;
		}
		
		return null;
	}
	
	public static Tileset load( String filename )
	{
		File f = new File( filename );
		
		try 
		{
			FileReader stream = new FileReader( f );
			BufferedReader buf = new BufferedReader( stream );

			String name = buf.readLine();
			
			LinkedList<String> list = new LinkedList<String>();
			
			String str;
			while( ( str = buf.readLine() ) != null )
			{
				list.add( str );
			}
			
			return new Tileset( name, list );
			
		} 
		catch ( FileNotFoundException e ) 
		{
			e.printStackTrace();
		} 
		catch ( IOException e ) 
		{
			e.printStackTrace();
		}
		
		return null;
	}
	
	public static Tileset load( Container frame )
	{
		JFileChooser fc = new JFileChooser();
		fc.setCurrentDirectory( new File( "C:/Documents and Settings/Owner/Desktop/Projects/Level Editor/TileSets" ) );
		int returnVal = fc.showOpenDialog( frame );
		
		if( returnVal == JFileChooser.APPROVE_OPTION )
		{
			load( fc.getSelectedFile().getAbsolutePath() );
		}
			
		return null;
	}
	
	public void save()
	{
		File f = new File( "TileSets/" + name + ".txt" );
		
		try 
		{ 
			f.createNewFile();
			BufferedWriter buf = new BufferedWriter( new FileWriter( f.getAbsolutePath() ) );
			
			String s = name;
			for( String str : tilesLocations )
			{
				s += "\n" + str;
			}
			
			buf.write( s );
			
			buf.close();
		} 
		catch ( FileNotFoundException err ) 
		{
			err.printStackTrace();
		} 
		catch ( IOException err ) 
		{
			err.printStackTrace();
		}
	}
	
	public String getName()
	{
		return name;
	}
	
	public LinkedList<String> getListTiles()
	{
		return tilesLocations;
	}
}
